package com.lg.algorithm.collections.tree;

public class TreeFun {

    public static TreeNode createTree() {
        TreeNode treeNode = new TreeNode("a");
        TreeNode treeNode1 = new TreeNode("b");
        TreeNode treeNode2 = new TreeNode("d");
        TreeNode treeNode3 = new TreeNode("e");
        TreeNode treeNode4 = new TreeNode("c");
        TreeNode treeNode5 = new TreeNode("f");
        TreeNode treeNode6 = new TreeNode("g");
        
        treeNode.setLeft(treeNode1);
        treeNode.setRight(treeNode4);
        treeNode1.setLeft(treeNode2);
        treeNode1.setRight(treeNode3);
        treeNode4.setRight(treeNode5);
        treeNode3.setLeft(treeNode6);
        return treeNode;
    }

    /**
     * 二叉查找树是会 旋转和变化的
     */
    public static  TreeNode createTreeByPreOrderAndInOrder(String preOder,String inOrder) {
//        if (preOder == null || preOder.equals("")) {
//            return null;
//        }

        if (preOder.isEmpty()) {
            return null;
        }
//        char c = preOder.toCharArray()[0];
        char c = preOder.charAt(0);
        TreeNode treeNode = new TreeNode(c + "");

        treeNode.setLeft(
                createTreeByPreOrderAndInOrder(
                    preOder.substring(1,inOrder.indexOf(c)+1),
                    inOrder.substring(0,inOrder.indexOf(c))
                )
        );

        treeNode.setRight(
                createTreeByPreOrderAndInOrder(
                        preOder.substring(inOrder.indexOf(c)+1),
                        inOrder.substring(inOrder.indexOf(c)+1)
                )
        );
        return treeNode;
    }

    /**
     * 树的 前序遍历
     */
    public  static  void prePrint(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        System.out.print(treeNode.getValue() + " ");
        prePrint(treeNode.getLeft());
        prePrint(treeNode.getRight());
    }

    public  static  void inPrint(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        inPrint(treeNode.getLeft());
        System.out.print(treeNode.getValue() + " ");
        inPrint(treeNode.getRight());

    }


    public  static  void postPrint(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        postPrint(treeNode.getLeft());
        postPrint(treeNode.getRight());
        System.out.print(treeNode.getValue() + " ");

    }
}
